package com.asktgapp.wxapi;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.asktgapp.MyConstant;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.dialog.CProgressDialogUtils;
import com.asktgapp.eventbus.PayFinishEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.HxAccountVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.PaySuccessActivity;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";

    private IWXAPI api;
    private TextView skip,tip;
    private TextView mStarChat;
    private HxAccountVO bean;
    private Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pay_success);
        mStarChat = findViewById(R.id.tv_back);
        tip = findViewById(R.id.tip);
        context = this;
        try {
            api = WXAPIFactory.createWXAPI(this, MyConstant.WEIXIN_AppID);
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            setIntent(intent);
            api.handleIntent(intent, this);

        } catch (Exception e) {

        }

    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                if( MyApplication.mAskType>2){
                    tip.setText("向 "+MyApplication.mAskEngineerName+" 付款成功");
                    mStarChat.setText("确定");
                    mStarChat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            WXPayEntryActivity.this.finish();
                        }
                    });
                }else {
                    loadData();
                }
                PayFinishEvent.postEvent(true);
            } else if (resp.errCode == -2) {
                PayFinishEvent.postEvent(false);
//                test1.setText("Code==" + resp.errCode);
//                Toast.makeText(this, "支付已取消！", Toast.LENGTH_LONG).show();
                WXPayEntryActivity.this.finish();
            } else {
//                test1.setText("Code==" + resp.errCode);
//                Toast.makeText(this, "支付未成功！", Toast.LENGTH_LONG).show();
//                skip.setClickable(false);
//                skip.setText("支付未成功");
                PayFinishEvent.postEvent(false);
                WXPayEntryActivity.this.finish();

            }
        }
    }

    private void loadData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();

//        if (Util.isEmpty(PreferencesUtil.getString(context, PreferencesUtil.USER_ID)) || Util.isEmpty(MyApplication.mAskEngineerID) || Util.isEmpty(MyApplication.mAskType + "")) {
//            showTost("缺少参数", 1);
//            return;
//        }
        params.put("userid", PreferencesUtil.getString(context, PreferencesUtil.USER_ID));
        params.put("chat_userid", MyApplication.mAskEngineerID);
        params.put("type", MyApplication.mAskType);
        params.put("is_type", 1);
        Call<ApiResponseBody<HxAccountVO>> call = apiservice.chatToUser(params);
        call.enqueue(new Callback<ApiResponseBody<HxAccountVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<HxAccountVO>> call, Response<ApiResponseBody<HxAccountVO>> response) {
                if (response.isSuccessful()) {
                    bean = response.body().getResult();
                    mStarChat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mStarChat.setClickable(false);
                            BiuEaseHelper
                                    .getInstance()
                                    .beginSingleChat(WXPayEntryActivity.this, "", bean.getProjector_hx(), MyApplication.mAskEngineerName
                                            , MyApplication.mAskEngineerHeadIMG, MyApplication.mAskEngineerID
                                            , 0, bean.getCid() + "", MyApplication.mAskType);
                            {
                                EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                                String action = "开始";//action可以自定义
                                EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);

                                String toUsername = bean.getProjector_hx();//发送给某个人
                                cmdMsg.setTo(toUsername);
                                cmdMsg.addBody(cmdBody);
                                EMClient.getInstance().chatManager().sendMessage(cmdMsg);
                            }
                            WXPayEntryActivity.this.finish();
                        }
                    });

                } else {
//                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<HxAccountVO>> call, Throwable t) {
//                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
//                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
//                } else if (apiException.isNetConnected()) {
//                    showSetNetworkSnackbar();
//                } else {
//                    showTost(apiException.getMessage(), 0);
//                }
            }
        });

    }


    @Override
    public void onReq(BaseReq baseReq) {

    }
}